/*!==========================================
 未认证微信号登录授权模块
 提供方法：doAuthorOperate 进行授权操作
			authorModify 修改授权操作
			simulatLogin 提交用户名和密码
============================================
*/
require( './style.less' );

define( [
  'jquery',
  'api',
  'message',
  'bigwe_utils',
  'bootstrap'
], function( $, api, ShowTitleMessage, bu ) {

  var returnParam = {};

  var ala = returnParam.$addLoginAuth = $( '#add_login_auth' ),
    qi = returnParam.$qrcodeImage = $( '#qrcode_image' ),
    vi = returnParam.$verifyImage = $( '#verify_image' );
  var intervalProcess,
    successCallback,
    outerParam;

  var apis = api.UNAUTHOR;

  var showTime = ShowTitleMessage.showTime;
  var md5 = bu.md5;

  ala.on( 'click', '.modal-footer .sure', function() {
    var account = $.trim( $( '#account', ala ).val() ),
      account_pwd = md5( $( '#account_pwd', ala ).val() );
    if ( !account_pwd || !account ) {
      ShowTitleMessage.showWarning( '请输入完整的微信公众号账户和密码', showTime );
    } else {
      returnParam.simulatLogin( {
        'login_account': account,
        'login_pwd': account_pwd
      }, successCallback );
    }

  } ).on( 'hidden.bs.modal', function() {
    if ( $.isFunction( returnParam.authorCancel ) ) {
      returnParam.authorCancel();
    }
  } ).on( 'show.bs.modal', function() {
    $( '.modal.fade[data-backdrop="static"]' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
  } ).on( 'keyup', '#account', function( e ) {
    e = e || event;
    if ( e.keyCode == 13 ) {
      $( '#account_pwd', ala ).trigger( 'focus' );
    }
  } ).on( 'keyup', '#account_pwd', function( e ) {
    e = e || event;
    if ( e.keyCode == 13 ) {
      $( '.sure', ala ).trigger( 'click' );
    }
  } );

  var viFn = undefined;

  var viSubmit = function( userAccount, success ) {
    return function() {
      var verify_code = $.trim( $( '#verify_code', vi ).val() );
      if ( verify_code.length != 4 ) {
        ShowTitleMessage.showWarning( '请输入正确长度的验证码', showTime );
        return;
      }
      returnParam.doAuthorOperate( $.extend( userAccount, {
        verify_code: verify_code
      } ), success );
    };
  };

  vi.on( 'click', '.modal-footer .ok', function() {
    if ( $.isFunction( viFn ) ) {
      viFn();
    } else {
      ShowTitleMessage.showWarning( '非法操作', showTime );
    }
  } ).on( 'hide.bs.modal', function() {
    $( '#verify_code', this ).val( '' );
  } ).on( 'hidden.bs.modal', function() {
    if ( $.isFunction( returnParam.authorCancel ) ) {
      returnParam.authorCancel();
    }
  } ).on( 'show.bs.modal', function() {
    ShowTitleMessage.show( '请输入验证码' );
    $( '.modal.fade[data-backdrop="static"]' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
  } ).on( 'click', '.verify_img', function() {
    $( '.verify_img', vi ).prop( 'src', apis.GRAB_VERIFY_IMG + outerParam.login_account );
  } ).on( 'keyup', '#verify_code', function( e ) {
    e = e || event;
    if ( e.keyCode == 13 ) {
      $( '.modal-footer .ok', vi ).trigger( 'click' );
    }
  } );

  qi.on( 'hide.bs.modal', function() {
    intervalProcess = 0;
    ShowTitleMessage.hide();
  } ).on( 'hidden.bs.modal', function() {
    if ( $.isFunction( returnParam.authorCancel ) ) {
      returnParam.authorCancel();
    }
  } ).on( 'show.bs.modal', function() {
    $( '.modal.fade[data-backdrop="static"]' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
    ShowTitleMessage.show( '请扫码授权' );
    intervalProcess = !0;
  } );
  $.extend( returnParam, {
    simulatLogin: function( userAccount, success ) {
      var me = this;
      ShowTitleMessage.show( '正在验证账户和密码' );
      $.extend( outerParam, userAccount );
      $.ajax( {
        type: 'POST',
        url: apis.CHECK_AUTH_ACCOUNT,
        data: {
          account: userAccount.login_account,
          account_pwd: userAccount.login_pwd
        },
        success: function( data ) {
          data = typeof data === 'string' ? $.parseJSON( data ) : data;
          if ( data.errcode == 0 ) {
            ala.removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
            me.doAuthorOperate( outerParam, success );
          } else if ( data.errcode == 1 ) {
            ShowTitleMessage.showWarning( '验证失败，请检查您的用户名密码！', showTime );
          } else if ( data.errcode == 2 ) {
            ala.removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
            vi.modal( 'show' );
            $( '.verify_img', vi ).prop( 'src', apis.GRAB_VERIFY_IMG + outerParam.login_account );
            viFn = viSubmit( outerParam, success );
          } else {
            ShowTitleMessage.showWarning( '验证失败！出现未知错误', showTime );
          }
        }
      } );
    },
    // 进行授权操作
    doAuthorOperate: function( userAccount, success ) {
      var me = this;
      successCallback = success;
      outerParam = $.extend( outerParam, userAccount );

      if ( !outerParam.login_account ) {
        $( 'div.modal.fade' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
        ala.modal( 'show' );
        return;
      }
      var postParam = {
        login_account: outerParam.login_account
      };
      if ( userAccount.verify_code ) {
        postParam.verify_code = userAccount.verify_code;
      }
      if ( userAccount.login_pwd ) {
        postParam.login_pwd = userAccount.login_pwd;
      }
      ShowTitleMessage.show( '正在进行授权验证！' );
      $.ajax( {
        type: 'POST',
        url: apis.SIM_LOGIN,
        data: postParam,
        success: function( data ) {

          if ( data.errcode == '0' ) {
            if ( outerParam.isNewAuthor ) {
              me._addAuthAccount( {
                account: outerParam.login_account,
                account_pwd: outerParam.login_pwd,
                original_id: data.original_id,
                app_id: outerParam.appid
              }, successCallback );
            } else {
              if ( $.isFunction( successCallback ) ) {
                successCallback.call( window, outerParam );
              }
            }
          } else if ( data.errcode == '1' ) {

            $( '.verify_img', vi ).prop( 'src', apis.GRAB_VERIFY_IMG + userAccount.login_account );
            if ( vi.css( 'display' ) == 'none' ) {
              vi.modal( 'show' );
              viFn = viSubmit( userAccount, successCallback );
            }

          } else if ( data.errcode == '2' ) {
            qi.modal( 'show' );
            $( '.qrcode', qi ).prop( 'src', data.url );
            me._checkScannerQi( userAccount, successCallback );
          } else if ( data.errcode == '4' ) {
            ShowTitleMessage.showWarning( '密码错误！', showTime );
            if ( ala.css( 'display' ) == 'none' ) {
              ala.modal( 'show' );
            }
          } else if ( data.errcode == '5' ) {
            ShowTitleMessage.showWarning( '验证码错误！', showTime );
            $( '#verify_code', vi ).trigger( 'focus' );
          } else {
            ShowTitleMessage.showWarning( '验证失败！出现未知错误', showTime );
          }
        }
      } );
    },
    // 修改授权
    authorModify: function( userAccount, success ) {
      /* eslint-disable no-unused-vars */
      var me = this;
      successCallback = success;
      outerParam = $.extend( outerParam, userAccount );
      if ( !userAccount.login_account ) {
        outerParam = $.extend( outerParam, {
          'isNewAuthor': !0
        } );
      } else {
        outerParam = $.extend( outerParam, {
          'isNewAuthor': 0
        } );
      }
      $( '#account', ala.modal( 'show' ) ).val( userAccount.login_account || '' );
      if ( userAccount.text ) {
        $( '.modal-title', ala ).text( userAccount.text );
      }
    },
    _checkScannerQi: function( userAccount, success ) {
      var me = this;
      $.ajax( {
        type: 'post',
        data: userAccount,
        url: apis.CHECK_QRCODE_STATUS,
        success: function( data ) {
          data = typeof data === 'string' ? $.parseJSON( data ) : data;

          if ( data.errcode != 0 ) {
            if ( intervalProcess ) {
              setTimeout( function() {
                me._checkScannerQi( userAccount, success );
              }, .5e3 );
            }
          }

          if ( data.errcode === '0' ) {
            qi.modal( 'hide' );
            me.confirm_flag = 0;
            ShowTitleMessage.hide();
            if ( userAccount.isNewAuthor || userAccount.login_pwd ) {
              // 每次都去修改用户授权账户或密码(2017年7月28日，Sherlcok)
              me._addAuthAccount( {
                account: userAccount.login_account,
                account_pwd: userAccount.login_pwd,
                original_id: data.original_id,
                app_id: outerParam.appid
              }, success );
            } else {
              if ( $.isFunction( success ) ) {
                success.call( window, userAccount );
              }
            }
          } else if ( data.errcode == 404 ) {
            if ( !me.confirm_flag ) {
              me.confirm_flag = !0;
              ShowTitleMessage.show( '请在手机上点击确认！' );
            }
          }

          if ( data == 500 ) {
            intervalProcess = 0;
          }
        }
      } );
    },
    _addAuthAccount: function( param, success ) {
      ShowTitleMessage.show( '验证成功！正在保存您的信息，便于下次操作' );
      ala.modal( 'hide' );
      $.ajax( {
        type: 'post',
        url: apis.ADD_AUTH_ACCOUNT,
        data: param,
        success: function( data ) {
          if ( data.errcode == 0 ) {
            $( '.fm_data', ala )[ 0 ].reset();
            if ( $.isFunction( success ) ) {
              success.call( window, outerParam );
            }
          } else if ( data.errcode == 2 ) {
            ShowTitleMessage.showWarning( '您当前账号与授权账号非同一账号！', showTime );
          } else {
            ShowTitleMessage.showWarning( '保存失败！请重试', showTime );
          }
        }
      } );
    }
  } );


  return returnParam;
} );
